package com.atguigu.tingshu.dispatch.job;
import java.util.Date;

import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.dispatch.service.XxlJobLogService;
import com.atguigu.tingshu.search.client.SearchFeignClient;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.google.common.collect.Maps;

import com.atguigu.tingshu.model.dispatch.XxlJobLog;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
public class DispatchJobHandler {

    @Autowired
    private XxlJobLogService xxlJobLogService;

    @Autowired
    private SearchFeignClient searchFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Transactional
    @XxlJob(value = "updateLatelyAlbumRanking-handler")
    public void updateLatelyAlbumRanking(){

        //获取任务Id
        long jobId = XxlJobHelper.getJobId();
        //创建Xxljob对象，用于封装保存的日志数据
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(jobId);

        //获取任务的开始执行时间
        long startTime = System.currentTimeMillis();

        //执行任务
        Result result = searchFeignClient.updateLatelyAlbumRanking();


        int resultcode = result.getCode().intValue();
        if (resultcode ==200){
            xxlJobLog.setStatus(1);
        }else {
            xxlJobLog.setStatus(0);
            xxlJobLog.setError(result.getMessage());

        }
        //获取任务的结束执行时间
        long endTime = System.currentTimeMillis();

        xxlJobLog.setTimes((int) (endTime-startTime));
        xxlJobLogService.save(xxlJobLog);

    }


    @Transactional
    @XxlJob(value = "updateVipExpireStatus-jobhandler")
    public void updateVipExpireStatus() {

        // 获取任务的id
        long jobId = XxlJobHelper.getJobId();

        // 创建一个XXLJobLog对象，封装要保存的日志数据
        XxlJobLog xxlJobLog = new XxlJobLog() ;
        xxlJobLog.setJobId(jobId);

        // 获取执行任务的时开始时间
        long startTime = System.currentTimeMillis();

        // 执行任务
        Result result = userInfoFeignClient.updateVipExpireStatus() ;

        if(result.getCode().intValue() == 200) {
            xxlJobLog.setStatus(1);
        }else {
            xxlJobLog.setStatus(0);
            xxlJobLog.setError(result.getMessage());
        }

        // 获取任务执行完毕以后的时间
        long endTime = System.currentTimeMillis();
        xxlJobLog.setTimes((int)(endTime - startTime));
        xxlJobLogService.save(xxlJobLog) ;

    }
}